from app.model.user.wtrees_group import GroupModel
from app.model.user.wtrees_group_permission import GroupPermissionModel
from app.model.user.wtrees_user import UserModel

from app.model.user.wtrees_user_group import UserGroupModel
from app.serve.user.permission import PermissionServer
from app.serve.wtrees.db import db
from sqlalchemy import func
from app.util.page import Page

from app.util.al import NotFound
from app.model.user.wtrees_permission import PermissionModel


class GroupServe(GroupModel):
    def _set_fields(self):
        self._exclude = ["delete_time", "create_time", "update_time"]

    @classmethod
    def group_user(cls, user_id) -> list:
        query = db.session.query(UserGroupModel.group_id) \
            .join(UserModel, UserModel.id == UserGroupModel.user_id) \
            .filter(UserModel is None, cls.id == user_id)
        result = cls.query.filter_by(soft=True).filter(cls.id.in_(query))
        groups = result.all()
        return groups

    @classmethod
    def group_count(cls, ids) -> int:
        result = db.session.query(func.count(cls.id)).filter(
            cls.id == ids, cls.delete_time is None
        )
        count = result.scalar()
        return count

    @classmethod
    def group_all(cls) -> list:
        query = cls.query
        groups = Page(query)
        if groups.items is None:
            raise NotFound("不存在任何分组")
        tmp = list()
        for group in groups.items:
            group = group.get_info()
            group['permissions'] = cls.group_permissions(group['id'])
            tmp.append(group)

        return tmp, groups.page_info(),

    @classmethod
    def group_permissions(cls, gid) -> list:
        query = db.session.query(PermissionModel).select_from(GroupPermissionModel) \
            .outerjoin(PermissionModel, PermissionModel.id == GroupPermissionModel.permission_id) \
            .filter(GroupPermissionModel.group_id == gid).all()
        ids = list()
        if query:
            for permission in query:
                if permission:
                    ids.append(permission.id)

        return ids

    @classmethod
    def create_group(cls, name, info, permission_ids, gid=None):
        exists = cls.get(name=name)
        # if exists:
        #     raise Forbidden("分组已存在，不可创建同名分组")

        if gid:
            group = cls.get(id=gid).update(name=name, info=info, commit=True)
        else:
            group = cls.create(name=name, info=info)
        db.session.flush()
        group_permission_list = list()
        de_Group = GroupPermissionModel.get(group_id=group.id)
        if de_Group:
            de_Group.delete(commit=True)
        for permission_id in permission_ids:
            if permission_id < 1000:
                gp = GroupPermissionModel()
                gp.group_id = group.id
                gp.permission_id = permission_id
                group_permission_list.append(gp)
        db.session.add_all(group_permission_list)
        db.session.commit()
